document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const videoPlayer = document.getElementById('video-player');
    const fileUpload = document.getElementById('file-upload');
    const uploadBtn = document.getElementById('upload-btn');
    const uploadStatus = document.getElementById('upload-status');
    const playBtn = document.getElementById('play-btn');
    const pauseBtn = document.getElementById('pause-btn');
    const progressBar = document.getElementById('progress-bar');
    const timeDisplay = document.getElementById('time-display');
    const roomInfo = document.getElementById('room-info');
    
    // 评分系统元素
    const overallStars = document.getElementById('overall-stars');
    const plotStars = document.getElementById('plot-stars');
    const actorsStars = document.getElementById('actors-stars');
    const soundStars = document.getElementById('sound-stars');
    const overallRating = document.getElementById('overall-rating');
    const plotRating = document.getElementById('plot-rating');
    const actorsRating = document.getElementById('actors-rating');
    const soundRating = document.getElementById('sound-rating');
    const ratingCount = document.getElementById('rating-count');
    
    // 评分输入元素
    const overallInput = document.getElementById('overall-input');
    const plotInput = document.getElementById('plot-input');
    const actorsInput = document.getElementById('actors-input');
    const soundInput = document.getElementById('sound-input');
    const overallRatingValue = document.getElementById('overall-rating-value');
    const plotRatingValue = document.getElementById('plot-rating-value');
    const actorsRatingValue = document.getElementById('actors-rating-value');
    const soundRatingValue = document.getElementById('sound-rating-value');
    const submitRatingBtn = document.getElementById('submit-rating-btn');
    const ratingStatus = document.getElementById('rating-status');
    
    // 全局变量
    let socket = null;
    let isDragging = false;
    
    // 创建Socket.IO连接
    function initSocket() {
        if (socket) return;
        
        socket = io();
        
        // Socket事件处理
        socket.on('connect', () => {
            console.log('Socket已连接');
            joinRoom();
        });
        
        socket.on('disconnect', () => {
            console.log('Socket已断开连接');
        });
        
        socket.on('room_status', (roomData) => {
            console.log('房间状态:', roomData);
            if (roomData.video_filename) {
                const videoUrl = `/videos/video_${roomData.video_filename}`;
                videoPlayer.src = videoUrl;
                videoPlayer.currentTime = roomData.current_time || 0;
                
                if (roomData.status === 'playing') {
                    videoPlayer.play();
                } else if (roomData.status === 'paused') {
                    videoPlayer.pause();
                }
            }
        });
        
        socket.on('video_uploaded', (data) => {
            console.log('视频已上传:', data);
            const videoUrl = `/videos/video_${data.filename}`;
            videoPlayer.src = videoUrl;
            updateTimeDisplay();
        });
        
        socket.on('play', (data) => {
            console.log('接收到播放命令:', data);
            videoPlayer.currentTime = data.current_time || 0;
            videoPlayer.play();
        });
        
        socket.on('pause', (data) => {
            console.log('接收到暂停命令:', data);
            videoPlayer.currentTime = data.current_time || 0;
            videoPlayer.pause();
        });
        
        socket.on('seek', (data) => {
            console.log('接收到进度调整命令:', data);
            if (!isDragging) {
                videoPlayer.currentTime = data.current_time || 0;
                updateProgressBar();
            }
        });
        
        socket.on('error', (data) => {
            console.error('错误:', data);
            alert(data.message || '发生错误');
        });
    }
    
    // 加入房间
    function joinRoom() {
        if (!socket) {
            initSocket();
        }
        
        socket.emit('join');
        roomInfo.textContent = '已连接到共享观看房间';
    }
    
    // 星星评分交互
    function setupStarRating() {
        // 为输入星星添加事件监听器
        const starInputs = document.querySelectorAll('.star-input');
        starInputs.forEach(star => {
            star.addEventListener('click', function() {
                const value = parseInt(this.getAttribute('data-value'));
                const parent = this.parentElement;
                const hiddenInput = parent.nextElementSibling;
                
                // 更新隐藏输入框的值
                hiddenInput.value = value;
                
                // 更新星星显示
                const stars = parent.querySelectorAll('.star-input');
                stars.forEach((s, index) => {
                    if (index < value) {
                        s.textContent = '★';
                    } else {
                        s.textContent = '☆';
                    }
                });
            });
        });
    }
    
    // 更新显示评分的星星
    function updateStarDisplay(starContainer, rating) {
        const stars = starContainer.querySelectorAll('.star');
        const fullStars = Math.floor(rating);
        const halfStar = rating % 1 >= 0.5;
        
        stars.forEach((star, index) => {
            star.classList.remove('filled');
            if (index < fullStars) {
                star.classList.add('filled');
            }
        });
    }
    
    // 提交评分
    submitRatingBtn.addEventListener('click', async function() {
        const overall = parseInt(overallRatingValue.value);
        const plot = parseInt(plotRatingValue.value);
        const actors = parseInt(actorsRatingValue.value);
        const sound = parseInt(soundRatingValue.value);
        
        // 验证输入
        if (overall === 0 || plot === 0 || actors === 0 || sound === 0) {
            ratingStatus.textContent = '请为所有评分项打分';
            ratingStatus.style.color = '#e74c3c';
            return;
        }
        
        // 将1-5分转换为1-10分
        const ratingsData = {
            overall: overall * 2,
            plot: plot * 2,
            actors: actors * 2,
            sound: sound * 2
        };
        
        try {
            const response = await fetch('/rating', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(ratingsData)
            });
            
            const result = await response.json();
            
            if (result.success) {
                ratingStatus.textContent = '评分提交成功！';
                ratingStatus.style.color = '#27ae60';
                
                // 清空输入框
                overallRatingValue.value = 0;
                plotRatingValue.value = 0;
                actorsRatingValue.value = 0;
                soundRatingValue.value = 0;
                
                // 重置星星显示
                const starInputs = document.querySelectorAll('.star-input');
                starInputs.forEach(star => {
                    star.textContent = '☆';
                });
                
                // 更新显示
                overallRating.textContent = (result.ratings.overall / 2).toFixed(1);
                plotRating.textContent = (result.ratings.plot / 2).toFixed(1);
                actorsRating.textContent = (result.ratings.actors / 2).toFixed(1);
                soundRating.textContent = (result.ratings.sound / 2).toFixed(1);
                ratingCount.textContent = result.count;
                
                // 更新星星显示
                updateStarDisplay(overallStars, result.ratings.overall / 2);
                updateStarDisplay(plotStars, result.ratings.plot / 2);
                updateStarDisplay(actorsStars, result.ratings.actors / 2);
                updateStarDisplay(soundStars, result.ratings.sound / 2);
            } else {
                ratingStatus.textContent = result.error || '评分提交失败';
                ratingStatus.style.color = '#e74c3c';
            }
        } catch (error) {
            console.error('评分提交错误:', error);
            ratingStatus.textContent = '评分提交失败，请重试';
            ratingStatus.style.color = '#e74c3c';
        }
    });
    
    // 上传视频 - 分片上传模式
    uploadBtn.addEventListener('click', async function() {
        const file = fileUpload.files[0];
        if (!file) {
            alert('请选择要上传的视频文件');
            return;
        }
        
        // 显示上传状态
        uploadStatus.textContent = '准备上传...';
        console.log(`开始上传文件: ${file.name}, 大小: ${formatFileSize(file.size)}`);
        
        // 分片大小设置为5MB，可根据需要调整
        const CHUNK_SIZE = 5 * 1024 * 1024;
        const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
        let uploadedChunks = 0;
        let fileId = null;
        
        try {
            // 1. 初始化上传
            uploadStatus.textContent = '初始化上传...';
            const initResponse = await initUpload(file.name, totalChunks);
            if (!initResponse.success) {
                throw new Error(initResponse.error || '初始化上传失败');
            }
            fileId = initResponse.file_id;
            console.log('上传初始化成功，文件ID:', fileId);
            
            // 2. 上传所有分片
            for (let i = 0; i < totalChunks; i++) {
                const start = i * CHUNK_SIZE;
                const end = Math.min(start + CHUNK_SIZE, file.size);
                const chunk = file.slice(start, end);
                
                // 更新状态
                const currentProgress = (i / totalChunks) * 100;
                uploadStatus.textContent = `上传分片 ${i + 1}/${totalChunks} (${currentProgress.toFixed(1)}%)`;
                
                // 上传分片
                const chunkResponse = await uploadChunk(fileId, i, chunk);
                if (!chunkResponse.success) {
                    throw new Error(chunkResponse.error || `分片 ${i} 上传失败`);
                }
                
                uploadedChunks++;
                console.log(`分片 ${i} 上传成功，已上传: ${uploadedChunks}/${totalChunks}`);
            }
            
            // 3. 完成上传，合并分片
            uploadStatus.textContent = '合并文件中...';
            const completeResponse = await completeUpload(fileId);
            if (!completeResponse.success) {
                throw new Error(completeResponse.error || '合并文件失败');
            }
            
            // 上传成功
            uploadStatus.textContent = '上传成功';
            updateTimeDisplay();
            console.log('文件上传完成');
        } catch (error) {
            console.error('上传错误:', error);
            uploadStatus.textContent = `上传失败: ${error.message}`;
            
            // 上传失败时尝试清理
            if (fileId) {
                console.log('尝试清理未完成的上传');
                // 这里可以添加一个清理API调用
            }
        }
    });
    
    // 初始化上传
    async function initUpload(filename, totalChunks) {
        try {
            const response = await fetch('/upload/init', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    filename: filename,
                    total_chunks: totalChunks
                })
            });
            
            if (!response.ok) {
                throw new Error(`HTTP错误 ${response.status}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error('初始化上传错误:', error);
            throw error;
        }
    }
    
    // 上传单个分片
    async function uploadChunk(fileId, chunkIndex, chunk) {
        try {
            const formData = new FormData();
            formData.append('file_id', fileId);
            formData.append('chunk_index', chunkIndex);
            formData.append('chunk', chunk);
            
            const response = await fetch('/upload/chunk', {
                method: 'POST',
                body: formData
            });
            
            if (!response.ok) {
                throw new Error(`HTTP错误 ${response.status}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error(`上传分片 ${chunkIndex} 错误:`, error);
            throw error;
        }
    }
    
    // 完成上传
    async function completeUpload(fileId) {
        try {
            const response = await fetch('/upload/complete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    file_id: fileId
                })
            });
            
            if (!response.ok) {
                throw new Error(`HTTP错误 ${response.status}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error('完成上传错误:', error);
            throw error;
        }
    }
    
    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    // 播放控制
    playBtn.addEventListener('click', function() {
        videoPlayer.play();
        if (socket) {
            socket.emit('play', {
                current_time: videoPlayer.currentTime
            });
        }
    });
    
    pauseBtn.addEventListener('click', function() {
        videoPlayer.pause();
        if (socket) {
            socket.emit('pause', {
                current_time: videoPlayer.currentTime
            });
        }
    });
    
    // 更新进度条
    function updateProgressBar() {
        if (!isDragging) {
            const percent = (videoPlayer.currentTime / videoPlayer.duration) * 100;
            progressBar.value = percent || 0;
        }
        updateTimeDisplay();
    }
    
    // 更新时间显示
    function updateTimeDisplay() {
        const current = formatTime(videoPlayer.currentTime);
        const duration = formatTime(videoPlayer.duration);
        timeDisplay.textContent = `${current} / ${duration}`;
    }
    
    // 格式化时间
    function formatTime(seconds) {
        if (isNaN(seconds)) return '00:00';
        const minutes = Math.floor(seconds / 60);
        const secs = Math.floor(seconds % 60);
        return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }
    
    // 进度条拖拽
    progressBar.addEventListener('mousedown', function() {
        isDragging = true;
    });
    
    progressBar.addEventListener('touchstart', function() {
        isDragging = true;
    });
    
    document.addEventListener('mouseup', function() {
        if (isDragging) {
            isDragging = false;
            updateVideoTime();
        }
    });
    
    document.addEventListener('touchend', function() {
        if (isDragging) {
            isDragging = false;
            updateVideoTime();
        }
    });
    
    progressBar.addEventListener('input', function() {
        if (isDragging) {
            updateTimeDisplay();
        }
    });
    
    // 更新视频时间
    function updateVideoTime() {
        const seekTime = (progressBar.value / 100) * videoPlayer.duration;
        videoPlayer.currentTime = seekTime;
        
        if (socket) {
            socket.emit('seek', {
                current_time: seekTime
            });
        }
    }
    
    // 视频时间更新事件
    videoPlayer.addEventListener('timeupdate', updateProgressBar);
    
    // 视频元数据加载完成
    videoPlayer.addEventListener('loadedmetadata', function() {
        progressBar.max = 100;
        progressBar.value = 0;
        updateTimeDisplay();
    });
    
    // 视频播放结束
    videoPlayer.addEventListener('ended', function() {
        if (socket) {
            socket.emit('pause', {
                current_time: 0
            });
        }
    });
    
    // 定期同步视频状态（每2秒）
    setInterval(function() {
        if (socket && videoPlayer.readyState >= 1) {
            // 只有当视频加载完成后才同步
            const syncData = {
                current_time: videoPlayer.currentTime,
                paused: videoPlayer.paused
            };
            socket.emit('sync_status', syncData);
        }
    }, 2000);
    
    // 初始化星星评分
    setupStarRating();
    
    // 初始化连接到默认房间
    initSocket();
});